from django.contrib.auth import authenticate, login
from django.views import View

from sportsground.utils import Req
from sportsground.utils.Res import Res


class LoginView(View):
    """ 登陆 """

    @Req.getJson
    def post(self, request):
        username = request.json_dict.get("username")
        password = request.json_dict.get("password")
        role = request.json_dict.get("role")

        account = authenticate(username, password=password, role=role)
        if not account:
            return Res.Json(Res.Warn, msg="用户名或密码错误")

        login(request, account)
        request.session.set_expiry(7 * 24 * 60 * 60)  # session 保留7天

        return Res.Json(Res.OK)
